package edu.dut.yz.webdemo.service;

import edu.dut.yz.webdemo.bean.Result;
import edu.dut.yz.webdemo.dao.SqlMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = RuntimeException.class)
public class SqlService {

    @Autowired
    SqlMapper sqlMapper;
    /**
     * for one parameter
     */
    public Result customizedSql(Map<String,Object> map){
        StringBuilder sql=new StringBuilder();
        sql.append("select ");
        Result result = new Result();
        List list=(ArrayList<Object>)map.get("what");
        int index=0;
        for(Object str : list){
            if(index!=0){
                sql.append(",");
            }
            sql.append((String)str);
            index++;
        }
        sql.append(" from ");
        String from=(String) map.get("from");
        sql.append(from);
        sql.append(" where ");
        index=0;
        Map where = (HashMap<String,String>)map.get("where");
        for(Object key : where.keySet()){
            if(index!=0){
                sql.append(" and ");
            }
            index++;
            sql.append((String)key);
            sql.append("=");
            sql.append((String)where.get(key));
        }
        sql.append(";");
        try {
            result.setDetails(sqlMapper.CustomizedSelect(sql.toString()));
            result.setSuccess(true);
        }catch (Exception e){
            result.setMsg(e.getMessage());
        }

        return result;
    }
}
